package com.fastgwt.server.dao;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fastgwt.shared.dto.Employee;



@Repository("employeeDAO")
public class EmployeeDAO extends JpaDAO<Long, Employee> {

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}

	@SuppressWarnings("unchecked")
	public List<Employee> listAll(String name, String surname, String job)
			throws Exception {

		String sql = "select emp from Employee emp ";
		String criteria = "";
		if (name != null && !"".equals(name)) {
			criteria = criteria + " emp.employeeName like  :name ";
		}
		if (surname != null && !"".equals(surname)) {
			if (!"".equals(criteria))
				criteria =  criteria + " and ";
			criteria = criteria + "emp.employeeSurname like :surname ";
		}

		if (job != null && !"".equals(job)) {
			if (!"".equals(criteria))
				criteria =  criteria + " and ";
			criteria = criteria + "emp.job like :jobDesc ";
		}

		if (!"".equals(criteria))
			sql += " where " + criteria;

		Query q = entityManagerFactory.createEntityManager().createQuery(sql);

		if (name != null && !"".equals(name))
			q.setParameter("name", "%" + name + "%");

		if (surname != null && !"".equals(surname))
			q.setParameter("surname", "%" + surname + "%");

		if (job != null && !"".equals(job))
			q.setParameter("jobDesc", "%" + job + "%");

		return q.getResultList();

	}
}